package com.nuotai.pms.common.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.nuotai.pms.common.entity.SysUserEntity;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Shiro工具类
 *
 * @author liujie
 */
public class ShiroUtils {
	
	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}
	
	public static SysUserEntity getUserEntity() {
		return (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
	}

	public static Long getUserId() {
		return getUserEntity().getUserId();
	}
	
	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static void logout() {
		SecurityUtils.getSubject().logout();
	}
	
	public static String getKaptcha(String key) {
		String kaptcha = getSessionAttribute(key).toString();
		getSession().removeAttribute(key);
		return kaptcha;
	}

	//获得主键
	public static String getUid(){
		return new SimpleDateFormat("yyMMddHHmmss").format(new Date())+getRandom(8);
	}
	//获取随机数从1开始,格式10000000-99999999
	public static int getRandom(int number){
		int max = 9;
		int min = 1;
		for (int i = 1; i < number; i++) {
			min = min * 10;
			max = max * 10 + 9;
		}
		return getRandom(min, max);
	}

	//获取随机数
	public static int getRandom(int min, int max) {
		// int a = (int) (Math.random() * (44) + 23); //产生的[23,67)的随机数
		return (int) (Math.random() * (max - min) + min);
	}

	//获取文件大小
	public static String convertFileSize(long size) {
		long kb = 1024;
		long mb = kb * 1024;
		long gb = mb * 1024;

		if (size >= gb) {
			return String.format("%.1f GB", (float) size / gb);
		} else if (size >= mb) {
			float f = (float) size / mb;
			return String.format(f > 100 ?"%.0f MB":"%.1f MB", f);
		} else if (size >= kb) {
			float f = (float) size / kb;
			return String.format(f > 100 ?"%.0f KB":"%.1f KB", f);
		} else
			return String.format("%d B", size);
	}
}
